package com.smartwebx.fr.controller;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.aspose.cells.License;
import com.smartwebx.fr.util.AsponExcelCellUtil;

@Controller
@RequestMapping("/exportExcel")
public class ExportExcelController {
	
	private boolean checkLicense;
		
	public ExportExcelController() {
		checkLicense = false;
		try {
			InputStream is = Resources
					.getResourceAsStream("\\aspose_excel_license.xml");
			License aposeLic = new License();
			aposeLic.setLicense(is);
			is.close();
			checkLicense = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/table")
	public ResponseEntity<byte[]> exportExcel(String dataType,String tableData) throws Exception{
		if (!checkLicense) {
			return null;
		}
		byte[] content = null;
		if("freeTable".equals(dataType)){
			content =  AsponExcelCellUtil.exportFreeTableExcel(tableData);
		}else if("table".equals(dataType)){
			content =  AsponExcelCellUtil.exportTableExcel(tableData);
		}
		
		String fileName = "下载.xlsx";
		if (content == null) {
			content = new byte[0];
			fileName = "导出错误.xlsx";
		}

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment",
				new String(fileName.getBytes(), "iso-8859-1"));
		return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
	}
}
